<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/28
 * Time: 16:15
 */

namespace app\index\server;


use app\index\model\Agent;
use app\index\model\AgentDaybook;
use app\index\model\Message;
use app\index\model\RechargeMember as RechargeMemberModel;
use app\index\model\User;
use app\index\model\UserDaybook;
use app\lib\exception\DatabaseException;
use think\Db;
use think\Exception;

class RechargeMemberServer extends BaseServer
{
    public function getList($params = [])
    {
        $params = $this->prep_param($params);
        try {
            // 总条数
            $count = RechargeMemberModel::count();
            $list = RechargeMemberModel::with(['user'])
                ->order($params['sort'], $params['order'])
                ->limit($params['offset'], $params['limit'])
                ->select();
        } catch (Exception $e) {
            // 有些问题 应该抛出错误异常
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return bootstrap_table_return($count, $list);
    }

    public function member_allocation($id)
    {
        // 拿到了用户的订单
        try {
            Db::startTrans();
            // 根据 id 号码获得 用户信息(包含上级代理和上上级代理的邀请码)
            $order_info = $this->getInfo($id);
            if(!$order_info) {
                return setMsg(0, '未找到此订单信息');
            }
            $order_no = $order_info->billno;
            // 获取总代理信息
            $agent_info = $this->agent($order_info->user->agent_id);
            if(!$agent_info) {
                return setMsg(0, '未找到总代理信息');
            }
            $billno = billno(); // 分成订单号
            $user_info = $order_info->user; // 用户信息(买家)
            $type = 'income'; // 分成定义为收入
            $price = '99'; // 分成金额
            $agent_to_daybook = [
                'agent_id' => $agent_info->id,
                'before_balance' => $agent_info->agent_balance,
            ];
            // TODO 有上级代理(NO) 上上级代理(NO) 总代理
            if($user_info->p_id == 0) {
                // 没有上级代理和上上级代理 只写总代理流水
                // 准备数据 分成价格 和分成比例
                $ratio = 1; // 总代理全部获得
                // 写总代理余额
                $agent_balance_result = $this->agent_balance($agent_info, $price, $ratio);
                if(!$agent_balance_result) {
                    Db::rollback();
                    return setMsg(0, '生成总代理余额失败');
                }
                $agent_to_daybook['after_balance'] = $agent_info->agent_balance;
                // 写总代理流水
                $agent_daybook = $this->agent_daybook($order_no, $user_info, $price, $ratio, $billno, $agent_to_daybook, $type);
                if(!$agent_daybook) {
                    Db::rollback();
                    return setMsg(0, '生成总代理流水失败');
                }
            }
            // TODO 有上级代理 上上级代理(NO) 总代理(OK)
            if($user_info->p_id !== 0 && $user_info->g_id == 0) {
                $ratio = 0.6;
                // 获得上一级代理信息
                $parent_info = $this->getUserInfo($user_info->p_id);
                if(!$parent_info) {
                    Db::rollback();
                    return setMsg(0, '上一级代理查询失败');
                }
                $parent_info_balance['before_balance'] = $parent_info->balance;
                // 增加上一级代理余额(这里分6成)
                $parent_balance = $this->changeUserBalance($parent_info, $price, $ratio);
                if(!$parent_balance) {
                    Db::rollback();
                    return setMsg(0, '新增上级代理余额失败');
                }
                $parent_info_balance['after_balance'] = $parent_info->balance;
                // 写上一级代理流水(6成)
                $parent_daybook = $this->userDaybook($order_no, $parent_info, $price, $ratio, $billno, $parent_info_balance, $type);
                if(!$parent_daybook) {
                    Db::rollback();
                    return setMsg(0, '写上一级分成流水失败');
                }
                // 给上一级代理发送消息
                $comment = '恭喜您获得了您的下线呢称为【' . $user_info->username . '】的会员分红【' . $price *  $ratio . '】元, 四眼文化祝您天天开心';
                $this->sendMsg($parent_info->id, '获得下线代理分红', $comment);
                // 写总代理余额(4成)
                $ratio = 0.4;
                $agent_balance_result = $this->agent_balance($agent_info, $price, $ratio);
                if(!$agent_balance_result) {
                    Db::rollback();
                    return setMsg(0, '生成总代理余额失败');
                }
                // 写总代理流水
                $agent_to_daybook['after_balance'] = $agent_info->agent_balance;
                $agent_daybook = $this->agent_daybook($order_no, $user_info, $price, $ratio, $billno, $agent_to_daybook, $type);
                if(!$agent_daybook) {
                    Db::rollback();
                    return setMsg(0, '生成总代理流水失败');
                }
            }
            // TODO 有上级代理 上上级代理 总代理
            if($user_info->p_id !== 0 && $user_info->g_id !== 0) {
                // 获得上一级代理信息
                $parent_info = $this->getUserInfo($user_info->p_id);
                $parent_info_balance['before_balance'] = $parent_info->balance;
                if(!$parent_info) {
                    Db::rollback();
                    return setMsg(0, '上一级代理查询失败');
                }
                $ratio = 0.6;
                // 写上一级代理余额(6成)
                $parent_balance = $this->changeUserBalance($parent_info, $price, $ratio);
                $parent_info_balance['after_balance'] = $parent_info->balance;
                if(!$parent_balance) {
                    Db::rollback();
                    return setMsg(0, '新增上级代理余额失败');
                }
                // 写上一级代理流水(6成)
                $parent_daybook = $this->userDaybook($order_no, $parent_info, $price, $ratio, $billno, $parent_info_balance, $type);
                if(!$parent_daybook) {
                    Db::rollback();
                    return setMsg(0, '写上一级分成流水失败');
                }
                // 给上一级代理发信息(6成)
                $comment = '恭喜您获得了您的下线呢称为【' . $user_info->username . '】的会员分红【' . $price * $ratio . '】元, 四眼文化祝您天天开心';
                $this->sendMsg($parent_info->id, '获得下线代理分红', $comment);
                // 获得上2级代理信息
                $grand_info = $this->getUserInfo($user_info->g_id);
                $grand_info_balance['before_balance'] = $grand_info->balance;
                if(!$grand_info) {
                    Db::rollback();
                    return setMsg(0, '上两级代理查询失败');
                }
                // 写上两级代理余额(6成)(3成)
                $ratio = 0.3;
                $grand_balance = $this->changeUserBalance($grand_info, $price, $ratio);
                $grand_info_balance['after_balance'] = $grand_info->balance;
                if(!$grand_balance) {
                    Db::rollback();
                    return setMsg(0, '新增上两级代理余额失败');
                }
                // 写上2级代理流水(3成)
                $grand_daybook = $this->userDaybook($order_no, $grand_info, $price, $ratio, $billno, $grand_info_balance, $type);
                if(!$grand_daybook) {
                    Db::rollback();
                    return setMsg(0, '写上一级分成流水失败');
                }
                // 给上一2级代理发信息(3成)
                $comment = '恭喜您获得了您的下线[' . $parent_info->username . ']发展的下线的呢称为【' . $user_info->username . '】的订单分红【' . $price * $ratio . '】元, 四眼文化祝您天天开心';
                $this->sendMsg($grand_info->id, '获得下线发展下线代理分红', $comment);
                // 写总代理余额(1成)
                $ratio = 0.1;
                $agent_balance_result = $this->agent_balance($agent_info, $price, $ratio);
                if(!$agent_balance_result) {
                    Db::rollback();
                    return setMsg(0, '生成总代理余额失败');
                }
                $agent_to_daybook['after_balance'] = $agent_info->agent_balance;
                // 写总代理流水(1成)
                $agent_daybook = $this->agent_daybook($order_no, $user_info, $price, $ratio, $billno, $agent_to_daybook, $type);
                if(!$agent_daybook) {
                    Db::rollback();
                    return setMsg(0, '生成总代理流水失败');
                }
            }
            // 把状态订单改为 已分成状态
            $order_info->allocation = 1;
            $result = $order_info->save();
            if($result) {
                Db::commit();
                return setMsg(1, '发送会员分红成功');
            }
        } catch (Exception $e) {
            throw new DatabaseException([
                'errorCode' => '',
                'msg' => $e->getMessage()
            ]);
        }
    }

    // 获得订单信息 用户信息
    public function getInfo($id)
    {
        try {
            $info = RechargeMemberModel::with(['user'])
                ->where('id', $id)
                ->find();
        } catch (Exception $e) {
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return $info;
    }

    // 总代理信息
    public function agent($id)
    {
        try {
            $info = Agent::where('id', $id)
                ->find();
        } catch (Exception $e) {
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return $info;
    }

    /**
     * @param $order_no 订单号(购买订单订单号)
     * @param $user_info 用户的 详细信息
     * @param $price 分成价格
     * @param $ratio 分成比例
     * @param $billno 订单号(新生成的分成订单号而不是买东西的订单号)
     * @param $agent_to_daybook 需要的流水信息
     * @param $type income outlay
     * @return int|string
     * @throws DatabaseException
     */
    public function agent_daybook($order_no, $user_info, $price, $ratio, $billno, $agent_to_daybook, $type)
    {
        try {
            // 进帐/出账价格
            $price = $price * 1000 * $ratio;
            $data = [
                'uid' => $user_info->id,
                'admin_uid' => session('Auth.Uid'),
                'billno' => $billno,
                'agent_id' => $agent_to_daybook['agent_id'],
                'before_balance' => $agent_to_daybook['before_balance'],
                'after_balance' => $agent_to_daybook['after_balance'],
                'description' => '用户名 : ' . $user_info->username . '的用户购买的订单号为' . $order_no . '为您分得比例为【' . $ratio . '】代理金【' . $price/1000 . '】元'
            ];
            if($type == 'income') {
                $data['income'] = $price/1000;
            }
            if($type == 'outlay') {
                $data['outlay'] = $price/1000;
            }
            $result = AgentDaybook::insert($data);
        } catch (Exception $e) {
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return $result;
    }

    // 写总代理余额
    public function agent_balance($agent_info, $price, $ratio)
    {
        $before_balance = $agent_info->agent_balance;
        // 代理获得收入
        $after_balance = ($before_balance * 1000 + $price * 1000 * $ratio)/1000;
        $agent_info->agent_balance = $after_balance;
        $result = $agent_info->save();
        return $result;
    }

    public function getUserInfo($id)
    {
        try {
            $user_info = User::where('id', $id)
                ->find();
        } catch (Exception $e) {
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return $user_info;
    }

    // 改变用户余额
    public function changeUserBalance($user_info, $price, $ratio)
    {
        $before_balance = $user_info->balance;
        // 代理获得收入
        $after_balance = ($before_balance * 1000 + $price * 1000 * $ratio)/1000;
        $user_info->balance = $after_balance;
        $result = $user_info->save();
        return $result;
    }

    // 增加用户余额流水
    public function userDaybook($order_no, $user_info, $price, $ratio, $billno, $parent_info_balance, $type)
    {
        try {
            // 进帐/出账价格
            $price = $price * 1000 * $ratio;
            $data = [
                'uid' => $user_info->id,
                'type' => 1, // 转入
                'admin_uid' => session('Auth.Uid'),
                'billno' => $billno,
                'before_balance' => $parent_info_balance['before_balance'],
                'after_balance' => $parent_info_balance['after_balance'],
                'description' => '用户名 : ' . $user_info->username . '的用户购买的订单号为' . $order_no . '为您分得代理金【' . $price/1000 . '】元, 比例为' . $ratio
            ];
            if($type == 'income') {
                $data['income'] = $price/1000;
            }
            if($type == 'outlay') {
                $data['outlay'] = $price/1000;
            }
            $result = UserDaybook::insert($data);
        } catch (Exception $e) {
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return $result;
    }

    public function sendMsg($id, $title, $comment)
    {
        $prep_data = [
            'uid' => $id,
            'admin_uid' => session('Auth.Uid'),
            'msg_title' => $title,
            'msg_contents' => $comment,
            'msg_from' => session('Auth.Uid'),
            'status' => 1
        ];
        try {
            $result = Message::insert($prep_data);
        } catch (Exception $e) {
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return $result;
    }
}